//
//  ALPS_CarouselFigureTool.m
//  Alps
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ALPS_CarouselFigureTool.h"


//获取ScrollView的X值偏移量
#define contentOffSet_x self.direct.contentOffset.x
//获取ScrollView的宽度
#define frame_width self.direct.frame.size.width
//获取ScrollView的contentSize宽度
#define contentSize_x self.direct.contentSize.width
@interface ALPS_CarouselFigureTool ()<UIScrollViewDelegate>
//轮播图片名字的数组
@property(strong,nonatomic) NSArray *imageArr;
//自定义视图的数组
@property(strong,nonatomic) NSArray *viewArr;
//定时器
@property(strong,nonatomic) NSTimer *timer;
//点击图片出发Block
@property(strong,nonatomic) imageClickBlock clickBlock;
@end

@implementation ALPS_CarouselFigureTool

#pragma mark 静态初始化方法
+(instancetype)direcWithtFrame:(CGRect)frame
                      ImageArr:(NSArray *)imageNameArray
            AndImageClickBlock:(imageClickBlock)clickBlock;
{
    return [[ALPS_CarouselFigureTool alloc]initWithtFrame:frame
                                              ImageArr:imageNameArray
                                    AndImageClickBlock:clickBlock];
}

#pragma mark 默认初始化方法
-(instancetype)initWithtFrame:(CGRect)frame
                     ImageArr:(NSArray *)imageNameArray
           AndImageClickBlock:(imageClickBlock)clickBlock;
{
    if(self = [self initWithFrame:frame])
    {
        
        //设置ScrollView的contentSize
        self.direct.contentSize = CGSizeMake((imageNameArray.count + 2) * frame_width, 0);
        
        //设置滚动图片数组
        self.imageArr = imageNameArray;
        
        //设置图片点击的Block
        self.clickBlock = clickBlock;
    }
    return self;
}

#pragma mark -  initWithFrame 初始化方法重写
-(instancetype)initWithFrame:(CGRect)frame
{
    if(self=[super initWithFrame:frame])
    {
        //初始化轮播ScrollView
        self.direct = [[UIScrollView alloc]init];
        self.direct.delegate = self;
        self.direct.pagingEnabled = YES;
        self.direct.frame = self.bounds;
        self.direct.scrollsToTop = NO;
        self.direct.contentOffset=CGPointMake(frame_width, 0);
        self.direct.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.direct];
        
        self.time = 4.0;
    }
    return self;
}

#pragma mark 初始化定时器
-(void)beginTimer
{
    if(self.timer == nil)
    {
        self.timer =[NSTimer scheduledTimerWithTimeInterval:self.time
                                                     target:self
                                                   selector:@selector(timerSel) userInfo:nil repeats:YES];
    }
}
#pragma mark 摧毁定时器
-(void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark 定时器调用的方法
-(void)timerSel
{
    //获取并且计算当前页码
    CGPoint currentConOffSet = self.direct.contentOffset;
    currentConOffSet.x += frame_width;
    
    //动画改变当前页码
    if (self.imageArr.count != 1) {
        [UIView animateWithDuration:0.5 animations:^{
            self.direct.contentOffset = currentConOffSet;
        }completion:^(BOOL finished) {
            [self updataWhenFirstOrLast];
        }];
    }
}

#pragma mark 判断是否第一或者最后一个图片,改变坐标
-(void)updataWhenFirstOrLast
{
    //当图片移动到最后一张时，动画结束移动到第二张图片的位置
    if(contentOffSet_x >= contentSize_x-frame_width)
    {
        self.direct.contentOffset = CGPointMake(frame_width, 0);
    }
    //当图片移动到第一张时，动画结束移动到倒数第二张的位置
    else if (contentOffSet_x <= 0)
    {
        self.direct.contentOffset = CGPointMake(contentSize_x - 2 * frame_width, 0);
    }
}

#pragma mark 开始拖拽代理
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}

#pragma mark 结束拖拽代理
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self beginTimer];
}

#pragma mark 结束滚动代理
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //当最后或者最前一张图片时改变坐标
    [self updataWhenFirstOrLast];
}


#pragma mark -=====================其他一些方法===================
#pragma mark轮播定时器时间
-(void)setTime:(CGFloat)time
{
    if(time > 0)
    {
        _time = time;
        [self stopTimer];
        [self beginTimer];
    }
}

#pragma mark 重写图片名字的数组
-(void)setImageArr:(NSArray *)imageArr
{
    if (_imageArr != imageArr) {
        _imageArr = imageArr;
    }
    [self addImageToScrollView];
    
    [self beginTimer];
}


#pragma mark 图片点击事件
-(void)imageClick:(UITapGestureRecognizer *)tap
{
    UIView *view = tap.view;
    if(self.clickBlock)
    {
        self.clickBlock(view.tag);
    }
}

#pragma mark 根据图片名添加图片到ScrollView
-(void)addImageToScrollView
{
    //创建一个可变数组
    NSMutableArray *imgMArr=[NSMutableArray arrayWithArray:self.imageArr];
    //添加第一个和最后一个对象到对应可变数组的最后一个位置和第一个位置
    [imgMArr insertObject:[self.imageArr lastObject] atIndex:0];
    [imgMArr addObject:[self.imageArr firstObject]];
    
    NSInteger tag = -1;
    if (imgMArr.count == 0)
    {
        return;
    }
    for (ALPS_FocusModel *model in imgMArr) {
        UIImageView *imgView = [[UIImageView alloc] init];
        [imgView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"ALPS"]];
        
        //设置图片的坐标
        imgView.frame = CGRectMake(self.frame.size.width * (tag + 1), 0, self.frame.size.width, self.frame.size.height);
        
        //添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageClick:)];
        
        //开启用户交互
        imgView.userInteractionEnabled = YES;
        
        [self.direct addSubview:imgView];
        
        [imgView addGestureRecognizer:tap];
        
        //设置tag
        imgView.tag = tag;
        tag++;
    }
}
@end
